package com.bartender.ingredient.service.impl;

import com.bartender.ingredient.service.IDifyService;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class DifyServiceImpl implements IDifyService {
    @Override
    public String getColor(String name) {
        try {
            // 创建 OkHttpClient 实例
//            OkHttpClient client = new OkHttpClient();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS) // 连接超时时间
                    .readTimeout(30, TimeUnit.SECONDS)    // 读取超时时间
                    .build();

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("inputs", new HashMap<>());
            requestBody.put("query", name + "的颜色");
            requestBody.put("response_mode", "streaming");
            requestBody.put("conversation_id", "");
            requestBody.put("user", "abc-123");

            // 将请求体转换为 JSON 字符串
            String jsonRequestBody = new Gson().toJson(requestBody);

            // 设置媒体类型
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

            // 构建 RequestBody
            RequestBody body = RequestBody.create(mediaType, jsonRequestBody);

            // 构建 Request
            Request request = new Request.Builder()
                    .url("https://dify.aipfuture.com/v1/chat-messages")
                    .header("Authorization", "Bearer app-klTBGn1JcMd9q0gzTOr8eQE3")
                    .post(body)
                    .build();

            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            int statusCode = response.code();
            String answer = "";
            // 检查状态码
            if (statusCode == 200) {
                // 读取响应流
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
//                StringBuilder completeAnswer = new StringBuilder();

                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject();
                        if (jsonObject.has("thought")) {
                            answer = jsonObject.get("thought").getAsString();
//                            completeAnswer.append(answer);
                            System.out.println("Complete Answer: " + answer);
                        }
                    }
                }

                // 输出完整答案
//                System.out.println("Complete Answer: " + completeAnswer.toString());
            } else {
                System.out.println("Request failed with status code: " + statusCode);
                return "";
            }

//            return responseBody;
            return answer;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
